package cn.org.xwb.bookmall.model.service.impl;

import cn.org.xwb.bookmall.model.constant.ProductConst;
import cn.org.xwb.bookmall.model.mapper.CommentsImgMapper;
import cn.org.xwb.bookmall.model.mapper.OrdersMapper;
import cn.org.xwb.bookmall.model.po.Comments;
import cn.org.xwb.bookmall.model.mapper.CommentsMapper;
import cn.org.xwb.bookmall.model.po.CommentsImg;
import cn.org.xwb.bookmall.model.po.Orders;
import cn.org.xwb.bookmall.model.service.ICommentsService;
import cn.org.xwb.bookmall.model.utils.BookRedisUtil;
import cn.org.xwb.bookmall.model.vo.CommentsVo;
import cn.org.xwb.bookmall.model.vo.OrderVo;
import cn.org.xwb.bookmall.model.vo.ProductCategoryVo;
import cn.org.xwb.common.redis.utils.RedisUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xwb
 * @since 2023-12-16
 */
@Service
public class CommentsServiceImpl extends ServiceImpl<CommentsMapper, Comments> implements ICommentsService {
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private BookRedisUtil bookRedisUtil;

    private String getKeyComment() {
        return bookRedisUtil.getRedisKeyUser("comment", "");
    }

    public List<CommentsVo> findAndCacheAll() {
        // 查询所有
        List<CommentsVo> commentsVos = baseMapper.selectAll();
        // 缓存
        Boolean res = redisUtil.setList(getKeyComment(), commentsVos);
        // 失败
        if (!res) return null;
        return commentsVos;
    }

    public List<CommentsVo> findAllFromCache() {
        // 查询缓存
        List<CommentsVo> commentsVos = (ArrayList<CommentsVo>) redisUtil.get(getKeyComment());
        // 缓存中不存在，则从数据库中查询，并缓存
        if (Objects.isNull(commentsVos)) commentsVos = findAndCacheAll();
        // 发生异常
        if (Objects.isNull(commentsVos)) return null;
        // 成功
        return commentsVos;
    }

    @Autowired
    private CommentsImgMapper commentsImgMapper;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrdersServiceImpl ordersService;

    @Transactional
    public Boolean addComment(Long orderId, Long productId, Long userId, String content, Integer score, List<String> img) {
        Comments comments = new Comments();
        comments.setProductId(productId);
        comments.setUserId(userId);
        comments.setScore(score);
        comments.setContent(content);
        comments.setCreateTime(new Date());
        comments.setUpdateTime(new Date());
        int res = baseMapper.insert(comments);
        if (res < 1) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        if (Objects.nonNull(img)) {
            for (String s : img) {
                CommentsImg commentsImg = new CommentsImg();
                commentsImg.setCommentId(comments.getId());
                commentsImg.setImgUrl(s);
                res = commentsImgMapper.insert(commentsImg);
                if (res < 1) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }
            }
        }
        Orders orders = new Orders();
        orders.setId(orderId);
        orders.setStatus(5);
        orders.setUpdateTime(new Date());
        boolean update = ordersService.updateById(orders);
        if (!update) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        List<OrderVo> orderVos = ordersService.findAndCacheAll();
        if (Objects.isNull(orderVos)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        List<CommentsVo> commentsVos = findAndCacheAll();
        if (Objects.isNull(commentsVos)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        return true;
    }

    @Transactional
    public Boolean delComment(Long id) {
        LambdaQueryWrapper<CommentsImg> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CommentsImg::getCommentId, id);
        commentsImgMapper.delete(wrapper);
        int res = baseMapper.deleteById(id);
        if (res < 1) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        List<CommentsVo> commentsVos = findAndCacheAll();
        if (Objects.isNull(commentsVos)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        return true;
    }

    public List<CommentsVo> getComments(Long productId, Long userId, String kw) {
        List<CommentsVo> commentsVos = findAllFromCache();
        if (Objects.nonNull(commentsVos)) Collections.reverse(commentsVos);
        if (Objects.nonNull(commentsVos) && Objects.nonNull(productId)) {
            commentsVos = commentsVos.stream().filter(commentVo -> commentVo.getProductId() == productId).toList();
        }
        if (Objects.nonNull(commentsVos) && Objects.nonNull(userId)) {
            commentsVos = commentsVos.stream().filter(commentVo -> commentVo.getUserId() == userId).toList();
        }
        return commentsVos;
    }
}
